// API基础配置
const API_BASE_URL = 'http://localhost:8080/api'

// 通用请求方法
const request = async (url, options = {}) => {
  const defaultOptions = {
    headers: {
      'Content-Type': 'application/json',
    },
  }
  
  const config = { ...defaultOptions, ...options }
  
  try {
    const response = await fetch(`${API_BASE_URL}${url}`, config)
    const data = await response.json()
    
    if (data.code === 200) {
      return data.data
    } else {
      throw new Error(data.message || '请求失败')
    }
  } catch (error) {
    console.error('API请求错误:', error)
    throw error
  }
}

// 新闻相关API
export const newsAPI = {
  // 获取首页新闻列表
  getHomeNews: (params = {}) => {
    const queryString = new URLSearchParams(params).toString()
    return request(`/news${queryString ? '?' + queryString : ''}`)
  },
  
  // 获取新闻详情
  getNewsDetail: (id) => {
    return request(`/news/${id}`)
  },
  
  // 获取指定信源的新闻列表
  getNewsBySource: (sourceId, params = {}) => {
    const queryString = new URLSearchParams(params).toString()
    return request(`/sources/${sourceId}/news${queryString ? '?' + queryString : ''}`)
  },
  
  // 搜索新闻
  searchNews: (params = {}) => {
    const queryString = new URLSearchParams(params).toString()
    return request(`/news/search${queryString ? '?' + queryString : ''}`)
  }
}

// 管理员新闻管理API
export const adminNewsAPI = {
  // 分页查询新闻列表
  getNewsPage: (queryDTO) => {
    return request('/admin/news/page', {
      method: 'POST',
      body: JSON.stringify(queryDTO)
    })
  },
  
  // 根据ID查询新闻详情
  getNewsById: (id) => {
    return request(`/admin/news/${id}`)
  },
  
  // 新增新闻
  addNews: (news) => {
    return request('/admin/news', {
      method: 'POST',
      body: JSON.stringify(news)
    })
  },
  
  // 更新新闻
  updateNews: (id, news) => {
    return request(`/admin/news/${id}`, {
      method: 'PUT',
      body: JSON.stringify(news)
    })
  },
  
  // 删除新闻
  deleteNews: (id) => {
    return request(`/admin/news/${id}`, {
      method: 'DELETE'
    })
  },
  
  // 批量删除新闻
  batchDeleteNews: (ids) => {
    return request('/admin/news/batch', {
      method: 'DELETE',
      body: JSON.stringify(ids)
    })
  },
  
  // 更新新闻状态
  updateNewsStatus: (id, status) => {
    const queryString = new URLSearchParams({ status }).toString()
    return request(`/admin/news/${id}/status?${queryString}`, {
      method: 'PUT'
    })
  },
  
  // 更新新闻热门状态
  updateNewsHot: (id, isHot) => {
    const queryString = new URLSearchParams({ isHot }).toString()
    return request(`/admin/news/${id}/hot?${queryString}`, {
      method: 'PUT'
    })
  }
}

// 分类相关API
export const categoryAPI = {
  // 分页查询分类
  getCategoryPage: (queryDTO) => {
    return request('/category/page', {
      method: 'POST',
      body: JSON.stringify(queryDTO)
    })
  },
  
  // 获取所有分类
  getAllCategories: () => {
    return request('/category/list')
  },
  
  // 获取所有分类（别名，用于兼容）
  getCategories: () => {
    return request('/category/list')
  },
  
  // 根据ID获取分类
  getCategoryById: (id) => {
    return request(`/category/${id}`)
  },
  
  // 根据名称获取分类
  getCategoryByName: (name) => {
    return request(`/category/name/${name}`)
  },
  
  // 根据编码获取分类
  getCategoryByCode: (code) => {
    return request(`/category/code/${code}`)
  },
  
  // 添加分类
  addCategory: (category) => {
    return request('/category', {
      method: 'POST',
      body: JSON.stringify(category)
    })
  },
  
  // 更新分类
  updateCategory: (id, category) => {
    return request(`/category/${id}`, {
      method: 'PUT',
      body: JSON.stringify(category)
    })
  },
  
  // 删除分类
  deleteCategory: (id) => {
    return request(`/category/${id}`, {
      method: 'DELETE'
    })
  },
  
  // 更新分类状态
  updateCategoryStatus: (id, status) => {
    const queryString = new URLSearchParams({ status }).toString()
    return request(`/category/${id}/status?${queryString}`, {
      method: 'PUT'
    })
  },
  
  // 批量删除分类
  batchDeleteCategories: (ids) => {
    return request('/category/batch', {
      method: 'DELETE',
      body: JSON.stringify(ids)
    })
  }
}

// 区域相关API
export const regionAPI = {
  // 分页查询区域
  getRegionPage: async (queryDTO) => {
    const response = await fetch(`${API_BASE_URL}/region/page`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(queryDTO)
    })
    return response.json()
  },
  
  // 获取所有区域
  getAllRegions: async () => {
    const response = await fetch(`${API_BASE_URL}/region/list`, {
      headers: { 'Content-Type': 'application/json' }
    })
    return response.json()
  },
  
  // 根据ID获取区域
  getRegionById: async (id) => {
    const response = await fetch(`${API_BASE_URL}/region/${id}`, {
      headers: { 'Content-Type': 'application/json' }
    })
    return response.json()
  },
  
  // 根据名称获取区域
  getRegionByName: async (name) => {
    const response = await fetch(`${API_BASE_URL}/region/name/${name}`, {
      headers: { 'Content-Type': 'application/json' }
    })
    return response.json()
  },
  
  // 根据代码获取区域
  getRegionByCode: async (code) => {
    const response = await fetch(`${API_BASE_URL}/region/code/${code}`, {
      headers: { 'Content-Type': 'application/json' }
    })
    return response.json()
  },
  
  // 添加区域
  addRegion: async (region) => {
    const response = await fetch(`${API_BASE_URL}/region`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(region)
    })
    return response.json()
  },
  
  // 更新区域
  updateRegion: async (id, region) => {
    const response = await fetch(`${API_BASE_URL}/region/${id}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(region)
    })
    return response.json()
  },
  
  // 删除区域
  deleteRegion: async (id) => {
    const response = await fetch(`${API_BASE_URL}/region/${id}`, {
      method: 'DELETE',
      headers: { 'Content-Type': 'application/json' }
    })
    return response.json()
  },
  
  // 更新区域状态
  updateRegionStatus: async (id, status) => {
    const queryString = new URLSearchParams({ status }).toString()
    const response = await fetch(`${API_BASE_URL}/region/${id}/status?${queryString}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' }
    })
    return response.json()
  },
  
  // 批量删除区域
  batchDeleteRegions: async (ids) => {
    const response = await fetch(`${API_BASE_URL}/region/batch`, {
      method: 'DELETE',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(ids)
    })
    return response.json()
  }
}

// 信源相关API
export const sourceAPI = {
  // 获取信源列表
  getSources: () => {
    return request('/sources')
  },
  
  // 获取新闻源卡片数据
  getSourceCards: () => {
    return request('/sources/cards')
  },
  
  // 获取分类列表
  getCategories: () => {
    return request('/categories')
  },

  // 分页查询新闻源列表
  getSourceList: async (queryDTO) => {
    const response = await fetch(`${API_BASE_URL}/source/list`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(queryDTO)
    })
    return response.json()
  },

  // 根据ID查询新闻源
  getSourceById: async (id) => {
    const response = await fetch(`${API_BASE_URL}/source/${id}`)
    return response.json()
  },

  // 新增新闻源
  addSource: async (source) => {
    const response = await fetch(`${API_BASE_URL}/source/add`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(source)
    })
    return response.json()
  },

  // 更新新闻源
  updateSource: async (source) => {
    const response = await fetch(`${API_BASE_URL}/source/update`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(source)
    })
    return response.json()
  },

  // 删除新闻源
  deleteSource: async (id) => {
    const response = await fetch(`${API_BASE_URL}/source/${id}`, {
      method: 'DELETE'
    })
    return response.json()
  },

  // 批量删除新闻源
  batchDeleteSources: async (ids) => {
    const response = await fetch(`${API_BASE_URL}/source/delete/batch`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(ids)
    })
    return response.json()
  },

  // 更新新闻源状态
  updateSourceStatus: async (id, status) => {
    const queryString = new URLSearchParams({ status }).toString()
    const response = await fetch(`${API_BASE_URL}/source/${id}/status?${queryString}`, {
      method: 'PUT'
    })
    return response.json()
  },

  // 获取所有启用的新闻源
  getAllEnabledSources: async () => {
    const response = await fetch(`${API_BASE_URL}/source/enabled`)
    return response.json()
  },

  // 根据区域ID查询新闻源
  getSourcesByRegionId: async (regionId) => {
    const response = await fetch(`${API_BASE_URL}/source/region/${regionId}`)
    return response.json()
  }
}

// 用户相关API
export const userAPI = {
  // 用户登录
  login: async (loginData) => {
    const response = await fetch(`${API_BASE_URL}/users/login`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(loginData)
    })
    return response.json()
  },

  // 获取当前用户信息
  getCurrentUser: async (userId) => {
    const response = await fetch(`${API_BASE_URL}/users/current?userId=${userId}`, {
      headers: { 'Content-Type': 'application/json' }
    })
    return response.json()
  },

  // 用户退出登录
  logout: async () => {
    const response = await fetch(`${API_BASE_URL}/users/logout`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' }
    })
    return response.json()
  },

  // 分页查询用户列表
  getUserPage: async (data) => {
    const response = await fetch(`${API_BASE_URL}/users/page`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data)
    })
    return response.json()
  },

  // 获取用户统计信息
  getUserStats: async () => {
    const response = await fetch(`${API_BASE_URL}/users/stats`, {
      headers: { 'Content-Type': 'application/json' }
    })
    return response.json()
  },

  // 添加用户
  addUser: async (data) => {
    const response = await fetch(`${API_BASE_URL}/users/add`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data)
    })
    return response.json()
  },

  // 更新用户信息
  updateUser: async (data) => {
    const response = await fetch(`${API_BASE_URL}/users/update`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data)
    })
    return response.json()
  },

  // 删除用户
  deleteUser: async (id) => {
    const response = await fetch(`${API_BASE_URL}/users/${id}`, {
      method: 'DELETE',
      headers: { 'Content-Type': 'application/json' }
    })
    return response.json()
  },

  // 批量删除用户
  deleteBatchUsers: async (ids) => {
    const response = await fetch(`${API_BASE_URL}/users/delete/batch`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(ids)
    })
    return response.json()
  },

  // 更新用户状态
  updateUserStatus: async (id, status) => {
    const response = await fetch(`${API_BASE_URL}/users/${id}/status?status=${status}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' }
    })
    return response.json()
  },

  // 批量更新用户状态
  updateBatchStatus: async (data) => {
    const response = await fetch(`${API_BASE_URL}/users/status/batch`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data)
    })
    return response.json()
  }
}

// Dashboard相关API
export const dashboardAPI = {
  // 获取仪表盘概览数据
  getOverview: async () => {
    const response = await fetch(`${API_BASE_URL}/dashboard/overview`, {
      headers: { 'Content-Type': 'application/json' }
    })
    return response.json()
  },

  // 获取新闻趋势数据
  getNewsTrend: async (period = 'day') => {
    const response = await fetch(`${API_BASE_URL}/dashboard/news-trend?period=${period}`, {
      headers: { 'Content-Type': 'application/json' }
    })
    return response.json()
  },

  // 获取信源分布数据
  getSourceDistribution: async () => {
    const response = await fetch(`${API_BASE_URL}/dashboard/source-distribution`, {
      headers: { 'Content-Type': 'application/json' }
    })
    return response.json()
  },

  // 获取分类统计数据
  getCategoryStats: async () => {
    const response = await fetch(`${API_BASE_URL}/dashboard/category-stats`, {
      headers: { 'Content-Type': 'application/json' }
    })
    return response.json()
  }
}

// 抓取任务视图 API（统一 Result 返回，使用 request 包装）
export const fetchTaskAPI = {
  // 分页获取任务视图
  getPage: (params = {}) => {
    // 过滤 undefined/null/空字符串，避免后端 Integer 解析 'undefined' 导致 400
    const cleaned = Object.fromEntries(
      Object.entries(params).filter(([_, v]) => v !== undefined && v !== null && v !== '')
    )
    const queryString = new URLSearchParams(cleaned).toString()
    return request(`/admin/fetch-tasks/page${queryString ? '?' + queryString : ''}`)
  },
  
  // 分页获取任务视图（带成功率统计）
  getPageWithSuccessRate: (params = {}) => {
    const cleaned = Object.fromEntries(
      Object.entries(params).filter(([_, v]) => v !== undefined && v !== null && v !== '')
    )
    const queryString = new URLSearchParams(cleaned).toString()
    return request(`/admin/fetch-tasks/page-with-success-rate${queryString ? '?' + queryString : ''}`)
  },
  
  // 手动触发抓取任务
  trigger: (feedId) => {
    return request(`/admin/fetch-tasks/${feedId}/trigger`, {
      method: 'POST'
    })
  },
  
  // 查询抓取任务状态
  getTaskStatus: (taskId) => {
    return request(`/admin/fetch-tasks/task/${taskId}/status`)
  }
}

// RSS 源管理 API（与后端 /api/admin/rss-feeds 对齐）
export const rssFeedAPI = {
  // 分页
  getPage: (queryDTO) => {
    return request('/admin/rss-feeds/page', {
      method: 'POST',
      body: JSON.stringify(queryDTO)
    })
  },
  // 详情
  getById: (id) => {
    return request(`/admin/rss-feeds/${id}`)
  },
  // 新增
  add: (data) => {
    return request('/admin/rss-feeds', {
      method: 'POST',
      body: JSON.stringify(data)
    })
  },
  // 更新
  update: (id, data) => {
    return request(`/admin/rss-feeds/${id}`, {
      method: 'PUT',
      body: JSON.stringify(data)
    })
  },
  // 软删除
  remove: (id) => {
    return request(`/admin/rss-feeds/${id}`, {
      method: 'DELETE'
    })
  },
  // 更新状态
  updateStatus: (id, status) => {
    const queryString = new URLSearchParams({ status }).toString()
    return request(`/admin/rss-feeds/${id}/status?${queryString}`, {
      method: 'PUT'
    })
  },
  // 获取启用列表
  getEnabled: () => {
    return request('/admin/rss-feeds/enabled')
  }
}

// 抓取日志 API
export const fetchLogAPI = {
  // 分页查询抓取日志
  getPage: (params = {}) => {
    const cleaned = Object.fromEntries(
      Object.entries(params).filter(([_, v]) => v !== undefined && v !== null && v !== '')
    )
    const queryString = new URLSearchParams(cleaned).toString()
    return request(`/admin/fetch-logs/page${queryString ? '?' + queryString : ''}`)
  },
  
  // 根据RSS源ID查询抓取日志
  getByFeedId: (rssFeedId, params = {}) => {
    const cleaned = Object.fromEntries(
      Object.entries(params).filter(([_, v]) => v !== undefined && v !== null && v !== '')
    )
    const queryString = new URLSearchParams(cleaned).toString()
    return request(`/admin/fetch-logs/feed/${rssFeedId}${queryString ? '?' + queryString : ''}`)
  },
  
  // 根据ID查询单条记录
  getById: (id) => {
    return request(`/admin/fetch-logs/${id}`)
  },
  
  // 删除单条记录
  deleteById: (id) => {
    return request(`/admin/fetch-logs/${id}`, {
      method: 'DELETE'
    })
  },
  
  // 批量删除记录
  deleteByIds: (ids) => {
    return request('/admin/fetch-logs/batch', {
      method: 'DELETE',
      body: JSON.stringify(ids)
    })
  },
  
  // 获取抓取统计信息
  getStatistics: (params = {}) => {
    const cleaned = Object.fromEntries(
      Object.entries(params).filter(([_, v]) => v !== undefined && v !== null && v !== '')
    )
    const queryString = new URLSearchParams(cleaned).toString()
    return request(`/admin/fetch-logs/statistics${queryString ? '?' + queryString : ''}`)
  },
  
  // 批量获取RSS源名称映射
  getRssFeedNames: (queryString) => {
    return request(`/admin/fetch-logs/rss-feed-names?${queryString}`)
  }
}

// 测试相关API
export const testAPI = {
  // 测试数据库连接
  testDatabase: () => {
    return request('/test/db')
  }
}
